package com.wangzh.concurrent.lock.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//线程按顺序执行
public class JUCA3 {

    public static void main(String[] args) {
        Data3 data3 = new Data3();
        new Thread(() ->{
            for (int i = 0; i < 10; i++) {
                data3.printA();
            }
        },"A").start();
        new Thread(() ->{
            for (int i = 0; i < 10; i++) {
                data3.printB();
            }
        },"B").start();
        new Thread(() ->{
            for (int i = 0; i < 10; i++) {
                data3.printC();
            }
        },"C").start();
    }
}
class Data3{
    private Lock lock = new ReentrantLock();
    Condition conditionA = lock.newCondition();
    Condition conditionB = lock.newCondition();
    Condition conditionC = lock.newCondition();

    private int number=1;
    public void printA(){
        lock.lock();

        try {
//            业务，判断--执行--通知
            while (number!=1){
//                等待
                conditionA.await();
            }
            System.out.println(Thread.currentThread().getName());
            number =2;
            conditionB.signal();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
    public void printB(){
        lock.lock();

        try {
//            业务，判断--执行--通知
            while (number!=2){
//                等待
                conditionB.await();
            }
            System.out.println(Thread.currentThread().getName());
            number =3;
            conditionC.signal();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
    public void printC(){
        lock.lock();

        try {
//            业务，判断--执行--通知
            while (number!=3){
//                等待
                conditionC.await();
            }
            System.out.println(Thread.currentThread().getName());
            number =1;
            conditionA.signal();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
}